layui.use(['layer', 'form'], function() {
    var layer = layui.layer;
    var form = layui.form;
    var verifyCode = $('.login-captcha');

    //验证码点击
    verifyCode.on('click',function () {
        this.src = this.src + '?t=' + (new Date).getTime();
    });

    //登录提交
    form.on('submit(login-submit)',function (obj) {
        var encryptKey = uuid(16,16);
        var params = {
                'userName': encrypt($('input[name="userName"]').val(),encryptKey),
                'passWord': encrypt($('input[name="passWord"]').val(),encryptKey),
                'verifyCode': encrypt($('input[name="verifyCode"]').val(),encryptKey),
                'encryptKey': encryptKey
        };
        layer.load(2);
        $.ajax({
            url: '/user/doLogin',
            type: 'POST',
            contentType: 'application/json; charset=UTF-8',// 解决415错误
            dataType: 'JSON',
            data: JSON.stringify(params),
            success: function(res) {
                if(res.code == '200') {
                    //请求成功后，写入 access_token
                    layui.data('blog', {//本地存储:向order表存储对象
                        key: 'token',
                        value: res.data
                    });
                    layer.msg(res.msg, {icon: 1, time: 500}, function () {
                       location.href = "/admin/main.html";
                    });
                }else { //登录失败
                    layer.closeAll('loading');
                    layer.msg(res.msg, {icon: 5, time: 1000});
                    //刷新验证码
                    verifyCode.attr('src','/user/genVerifyCode?t=' + (new Date).getTime())
                }
            },
            error: function(error) {
                layer.closeAll('loading');
                layer.msg(error.msg, {icon: 5, time: 1000});
            }
        });

        return false;
    });

});